package org.porridge.module.main.action;

import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.porridge.module.fun.business.FunBusiness;
import org.porridge.module.fun.po.Fun;
import org.porridge.module.main.business.UserBusiness;
import org.porridge.module.main.po.User;
import org.porridge.util.ImgCodeUtil;
import org.porridge.util.MD5;
import org.porridge.util.jqgrid.GridPO;
import org.porridge.util.jqgrid.JqgridUtil;
import org.transmit.ActionContext;
import org.transmit.ActionUtil;
import org.transmit.form.vali.ValidationPage;
import org.transmit.key.Action;
import org.transmit.key.Business;
import org.transmit.key.Parameters;
import org.transmit.key.Results;
import org.transmit.key.ReturnJSON;
import org.transmit.key.ReturnText;


/**
 * 用户登录处理action
* @Title: UserAction.java 
* @Package org.porridge.module.main.action 
* @Description: TODO 
* @author porridge
* @url  http://www.prdblog.com/
* @email  mfkwfc@gmail.com   
* @date 2014年4月15日 下午10:54:44 
* @version V1.0
 */
@Action("module")
@Results({@Parameters(location = "/pages/login.jsp", name = "login")})
public class UserAction {
	@Business
	private UserBusiness userbusiness;
	@Business
	private FunBusiness funbusiness;
	/**
	 * 退出登录
	 */
	public String logout(){
		HttpSession session=ActionContext.getSession();
		Enumeration enumsession=session.getAttributeNames();
		while (enumsession.hasMoreElements()){//删除所有的session  
			session.removeAttribute(enumsession.nextElement().toString());
		}
		return "login";
	}
	/**
	 * 用户登录 
	 * 
	 * @return  0成功登录  1用户名或密码为空  2用户或密码错误  3验证码错误  4数据库连接错误
	 * @throws SQLException 
	 */
	@ReturnText
	public String userLogin() throws SQLException{
		User user=ActionUtil.find(User.class);
		String ret="1";
		HttpSession session=ActionContext.getSession();
		//第一步判断是否有验证码
		Object valimg=session.getAttribute("valiimg");
		if(valimg!=null && "true".equals(valimg.toString())){
			ret="3";
			Object imgcode=ActionContext.getRequest().getParameter("imgcode");
			if(imgcode!=null){
				if(ImgCodeUtil.valiimgcode(imgcode.toString(),session.getId()))
					ret="0";
			}
		}
		//第二步判断用户名和登录密码
		if(!"3".equals(ret) && user!=null && user.getUsername()!=null && user.getPasword()!=null){
			try {
				user=userbusiness.userLogin(user.getUsername(),user.getPasword());
				if(user==null){//如果用户名或密码错误则显示验证码
					ret="2";
					session.setAttribute("valiimg",true);
				}else{
					Map<String,List<Fun>> funmap=this.funbusiness.findUserFun(user);
					session.setAttribute("funmap",funmap);
					session.setAttribute("user",user);
					session.removeAttribute("valiimg");
					ret="0";
				}
			} catch (Exception e) {
				e.printStackTrace();
				ret="4";
			}
		}
		return ret;
	}
	/**
	 * 显示验证码
	 */
	public void getimgcode(){
		try {
			ImgCodeUtil.setCodeImages(ActionContext.getResponse(),ActionContext.getSession().getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 查询出表格数据
	 * @return
	 * @throws Exception 
	 */
	@ReturnText
	public String userjqgrid() throws Exception{
		GridPO grid;
		String ret="";
		grid = JqgridUtil.getGridPath();
		if(grid!=null)
			ret=this.userbusiness.jqgrid(grid);
		return ret;
	}
	 /**
	  * 用户注册保存
	  */
	 public void saveUser(){
		 User user=ActionUtil.find(User.class);
		 Object obj=ActionContext.getRequest().getParameter("pasword1");
		 PrintWriter out=ActionContext.getPrintWriter();
		 if(ValidationPage.ValidationPO(user)){
			 user.setId(null);
			 String ret="{\"result\":false,\"name\":null,\"text\":\"注册用户失败\"}";
			 try{
				 if(obj!=null && !user.getPasword().equals(obj.toString())){
					 ret="{\"result\":false,\"name\":\"pasword1\",\"text\":\"密码不相同,请重试\"}";
				 }else if(this.userbusiness.findUserCount(user)){
					 ret="{\"result\":false,\"name\":\"username\",\"text\":\"登录名已存在,请换一个登录名\"}";
				 }else{
					 boolean bl=this.userbusiness.saveUser(user);
					 ret="{\"result\":"+bl+",\"name\":null,\"text\":\""+(bl?"注册用户成功":"用户注册失败,请重试")+"\"}";
				 }
			 } catch (Exception e) {
				e.printStackTrace();
			}finally{
				out.print(ret);
			}
		 }
	 }
	 /**
	  * 查询单个用户
	  * @return
	  */
	 @ReturnJSON
	 public User findUser(){
		 User user=null;
		 Object id=ActionContext.getRequest().getParameter("id");
		 if(id!=null && id.toString().trim().length()>0){
			 try {
				user=this.userbusiness.findUser(id.toString().trim());
				if(user!=null)
					user.setPasword(null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		 }
		 return user;
	 }
	 /**
	  * 修改单个用户
	  * @return
	 * @throws Exception 
	  */
	 public void updateUser() throws Exception{
		 User user=ActionUtil.find(User.class);
		 PrintWriter out=ActionContext.getPrintWriter();
		 if(ValidationPage.ValidationPO(user,"pasword")){
			 String ret="{\"result\":false,\"name\":null,\"text\":\"修改用户失败\"}";
			 	 user.setPasword(null);
				 if(this.userbusiness.updateUser(user))
					 ret="{\"result\":true}";
				out.print(ret);
		 }
	 }
	 /**
	  * 删除用户
	  * @return
	  */
	 @ReturnText
	 public String delUser(){
		 User user=ActionUtil.find(User.class);
		 boolean bl=false;
		 if(user!=null && user.getId()!=null){
			 try {
				bl=this.userbusiness.delUser(user);
			} catch (Exception e) {
				e.printStackTrace();
			}
		 }
		 return String.valueOf(bl);
	 }
	 /**
	  * 修改员工基本信息
	 * @throws Exception 
	  */
	 public void setuserbase() throws Exception{
		 User user=ActionUtil.find(User.class);
		 if(ValidationPage.ValidationPO(user,"username,pasword,unitid")){
			 User user1=(User) ActionContext.getSession().getAttribute("user");
			 String ret="{\"result\":false,\"name\":null,\"text\":\"修改个人信息失败,未知错误\"}";
			 PrintWriter out=ActionContext.getPrintWriter();
			 if(user1!=null){
				 user.setId(user1.getId());
				 user.setUsername(null);
				 user.setPasword(null);
				 user.setUnitid(null);
				 if(this.userbusiness.updatePo(user)>0)
					 ret="{\"result\":true}";
			 }
			 out.print(ret);
		 }
	 }
	 /**
	  * 修改登录用户密码
	 * @throws Exception 
	  */
	 public void setuserpassword() throws Exception{
		 HttpServletRequest request=ActionContext.getRequest();
		 String pas=request.getParameter("pasword");
		 String pas1=request.getParameter("pasword1");
		 String pas2=request.getParameter("pasword2");
		 User user1=(User) ActionContext.getSession().getAttribute("user");
		 PrintWriter out=ActionContext.getPrintWriter();
		 String ret="{\"result\":false,\"name\":null,\"text\":\"修改个人密码失败,未知错误\"}";
		 if(user1==null){
			 out.print(ret);
			 return;
		 }
		User user=this.userbusiness.findUserpassword(user1.getId());
		if(!(pas!=null && user!=null && user.getPasword()!=null
			    && user.getPasword().toLowerCase().equals(new MD5().getMD5ofStr(pas).toLowerCase()))){
			ret="{\"result\":false,\"name\":\"pasword\",\"text\":\"旧密码输入错误\"}";
			out.print(ret);
			return;
		 }
		 if(pas1!=null &&  pas1.trim().length()>0 && pas1.equals(pas2)){
			 user.setPasword(new MD5().getMD5ofStr(pas1));
			 if(this.userbusiness.updatePo(user)>0)
				 ret="{\"result\":true}";
			 else
				 ret="{\"result\":false,\"name\":\"pasword\",\"text\":\"修改密码失败\"}";
		 }else{
			 ret="{\"result\":false,\"name\":\"pasword1\",\"text\":\"新密码输入必须一致并且不能为空\"}";					 
		 }
		 out.print(ret);
	 }
}
